import { ChangeDetectorRef, Directive, Injector, OnDestroy, OnInit, TemplateRef, ViewChild } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { STChange, STPage, STWidthMode } from '@delon/abc/st';
import { XlsxService } from '@delon/abc/xlsx';
import { DA_SERVICE_TOKEN, JWTTokenModel } from '@delon/auth';
import { SFButton } from '@delon/form';
import { _HttpClient } from '@delon/theme';
import { NzDrawerService } from 'ng-zorro-antd/drawer';
import { NzMessageService } from 'ng-zorro-antd/message';
import { NzModalService } from 'ng-zorro-antd/modal';
import { NzNotificationService } from 'ng-zorro-antd/notification';

import { LoggerService, ShowModalService, UserService } from '../services';
import { AbstractApiUrlDataService } from './abstract-api-url.service';
import { ScrollParams } from './interface';

/**
 * 基础Component控件,主要处理一些基础通用的问题，比如，退出路由时，关闭modal
 */
@Directive()
export abstract class BaseOfSimpleComponent implements OnInit, OnDestroy {
    abstract apiUrl: AbstractApiUrlDataService;

    @ViewChild('notice', { static: false }) noticeCard!: TemplateRef<{}>;

    // 版面全屏操作
    scroll: ScrollParams = { x: '1000px', y: '400px' };

    // 表格宽度模式
    widthMode: STWidthMode = {
        type: 'strict',
        strictBehavior: 'truncate'
    };

    // 翻页设置项
    pageSet: STPage = {
        placement: 'center',
        show: true,
        showSize: true,
        showQuickJumper: true,
        total: true
    };

    // 表格单选选中的对象
    singleCheckedItem: any;

    sfSearchBtns: SFButton = {
        search: '查询'
    };

    // 是否在加载数据
    public loading = false;

    // 表格边框
    public bordered = true;

    // 默认分页数
    public ps = 10;

    // 表格尺寸
    public tableSize: 'small' | 'middle' | 'default' = 'small';

    // 表格中多选的对象
    multipleCheckedItems: any = [];

    userSer: UserService;
    msg: NzMessageService;
    modalSrv: NzModalService;
    modal: ShowModalService;
    log: LoggerService;
    client: _HttpClient;
    cdRef: ChangeDetectorRef;
    notification: NzNotificationService;
    router: Router;
    drawerSer: NzDrawerService;
    actRoute: ActivatedRoute;
    xlsx: XlsxService;

    protected constructor(protected injector: Injector) {
        this.userSer = this.injector.get(UserService);
        this.msg = this.injector.get(NzMessageService);
        this.log = this.injector.get(LoggerService);
        this.modalSrv = this.injector.get(NzModalService);
        this.drawerSer = this.injector.get(NzDrawerService);
        this.modal = this.injector.get(ShowModalService);
        this.client = this.injector.get(_HttpClient);
        this.cdRef = this.injector.get(ChangeDetectorRef);
        this.router = this.injector.get(Router);
        this.notification = this.injector.get(NzNotificationService);
        this.actRoute = this.injector.get(ActivatedRoute);
        this.xlsx = this.injector.get(XlsxService);
    }

    ngOnInit(): void {
        this.log.logMsg('BaseOfSimpleComponent - ngOnInit');
    }

    ngOnDestroy(): void {
        // this.modalSrv.closeAll();
        this.log.logMsg('BaseOfSimpleComponent - ngOnDestroy');
    }

    /**
     * 预览图片
     */
    handlePreview = (img_url: string) => {
        this.injector.get(NzModalService).create({
            nzContent: `<img src="${img_url}" class="img-fluid" />`,
            nzFooter: null
        });
    };

    /**
     * 重新加载页面
     */
    reloadPage(): void {
        window.location.reload();
    }

    /**
     * 路由复用的一些方法
     */
    _onReuseInit(): void {
        this.ngOnInit();
    }

    /**
     * 路由复用的一些方法
     */
    _onReuseDestroy(): void {
        this.ngOnDestroy();
    }

    /**
     * ST数据筛选框
     */
    simpleTableCheck(event: STChange): void {
        if (event.type === 'radio') {
            this.singleCheckedItem = event.radio;
        } else if (event.type === 'loaded') {
            this.singleCheckedItem = null;
            this.multipleCheckedItems = [];
        } else if (event.type === 'checkbox') {
            this.multipleCheckedItems = event.checkbox;
            if (this.multipleCheckedItems.length === 1) {
                this.singleCheckedItem = event.checkbox ? event.checkbox[0] : null;
            } else {
                this.singleCheckedItem = null;
            }
        }
    }

    /**
     * 处理参数，并加入token，将token放入url
     */
    parseParams(data: any): string {
        const model = this.injector.get(DA_SERVICE_TOKEN).get<JWTTokenModel>(JWTTokenModel);
        try {
            const tempArr = [];
            // tslint:disable-next-line: forin
            for (const i in data) {
                const key = encodeURIComponent(i);
                const value = encodeURIComponent(data[i]);
                tempArr.push(`${key}=${value}`);
            }
            tempArr.push(`${'token' + '='}${model.token}`);
            return tempArr.join('&');
        } catch (err) {
            return '';
        }
    }

    /**
     * 全屏切换
     *
     * @param val boolean
     */
    fullChange(val: boolean): void {
        this.scroll = val ? { x: '2000px', y: '400px' } : { x: '1800px', y: '600px' };
    }
}
